//
//  TuyaLoginFlow.swift
//  casdon_swiftUI
//
//  Created by ww on 2025/4/16.
//

import Combine

// 帐号密码登陆流程
final class PwdLoginFlow {
    private let cdPwdLoginStep:   CDPwdLoginStep        // 第一步，调用凯度云账户密码登录
    private let cdGetUserInfoStep: CDGetUserLoginInfoStep    // 第二步，调用凯度云服务获取用户信息
    private let tuyaLoginPwdStep: TuyaLoginPwdStep      // 第三步，涂鸦账户密码登录
    
    init() {
        cdPwdLoginStep = CDPwdLoginStep()
        cdGetUserInfoStep = CDGetUserLoginInfoStep()
        tuyaLoginPwdStep = TuyaLoginPwdStep()
    }
    
    func start(userName: String, password: String) -> AnyPublisher<Void, Error> {
        cdPwdLoginStep.execute(.init(userName: userName, password: password))
            .flatMap { [weak self] response -> AnyPublisher<AuthAPI.UserLogInInfo.Response, Error> in
                AuthManager.shared.saveToken(response.access_token)
                return self?.cdGetUserInfoStep.execute(.init()) ?? Fail(error: FlowError.stepMissing).eraseToAnyPublisher()
            }
            .flatMap { [weak self] userInfo -> AnyPublisher<Void, Error> in
                return self?.tuyaLoginPwdStep.execute(.init(account:  userInfo.userName, password: userInfo.password)) ?? Fail(error: FlowError.stepMissing).eraseToAnyPublisher()
            }
            .eraseToAnyPublisher()
    }
}



